<script lang="ts" setup>
import { CheckmarkOutline, Password } from '@vicons/carbon';

import { columns, formSchemas, roleColumns, searchSchemas } from './meta';

import type { DataActionButtons } from '@/components/crud';
import { BasicCrud } from '@/components/crud';
import {
  addUser,
  delUser,
  deptTreeSelect,
  getAuthRole,
  listUser,
  resetUserPwd,
  updateAuthRole,
  updateUser,
} from '@/api/system/user';
import { listRole } from '@/api/system/role';
import { useGridColumns } from '@/hooks/event/use-grid-columns';
import { computeResponsiveColumns } from '@/utils/responsive-util';
import BasicTree from '@/components/tree/index.vue';
import { useContentHeight } from '@/hooks/event/use-content-height';
import { usePageDataStore } from '@/store/modules/page-data';
import type { ActionButton } from '@/components/table/src/types/action-button';
import { errorMessage, successMessage } from '@/hooks/naive/ui-helper';
import { BasicModal, useModal } from '@/components/modal';
import BasicTable from '@/components/table/src/table.vue';

defineOptions({
  name: 'UserPage',
});

/**
 * 部门选择
 */
const departmentId = ref<string | number | undefined>();
function handleDepartmentSelect(value: string | number | undefined) {
  departmentId.value = value;
}
const requestParams = computed(() => {
  return {
    deptId: departmentId.value,
  };
});
function handleDepartmentAfterFetch(data: Recordable[]) {
  usePageDataStore().set('departmentTreeData', data);
}

/**
 * 分配角色
 */
const [register, { openModal, closeModal, setLoading }] = useModal({
  title: '分配角色',
});
const currentUserId = ref<string>();
const selectedRoles = ref<Array<string | number>>([]);
const defaultSelectedRoles = ref<Array<string | number>>([]);
async function fetchAuthRole() {
  if (!currentUserId.value) {
    return;
  }
  getAuthRole(currentUserId.value)
    .then(({ data }) => {
      defaultSelectedRoles.value = data.roles.map(item => item.roleId);
      openModal();
    });
}

function handleSelectRoles(values: Array<string | number>) {
  selectedRoles.value = values;
}
async function handleAssignRoles() {
  if (!currentUserId.value) {
    return;
  }
  const roleIds = selectedRoles.value.join(',');

  try {
    await updateAuthRole({ userId: currentUserId.value, roleIds });
    successMessage('分配成功');
  } finally {
    setLoading(false);
    closeModal();
  }
}

/**
 * 数据操作按钮
 */
const dataActionButtons: DataActionButtons = ({ modifyButton, deleteButton }) => {
  const resetPassword = shallowReactive<ActionButton>({
    name: '重置密码',
    key: 'resetPassword',
    icon: Password,
    onClick: async rowData => {
      try {
        await resetUserPwd(rowData?.userId, '123456');
        successMessage('重置成功');
      } catch (error) {
        errorMessage(`重置失败， ${error}`);
      }
    },
  });

  const assignRoles = shallowReactive<ActionButton>({
    name: '分配角色',
    key: 'assignRoles',
    icon: CheckmarkOutline,
    onClick: async rowData => {
      currentUserId.value = rowData?.userId;
      await fetchAuthRole();
    },
  });
  return [modifyButton, deleteButton, resetPassword, assignRoles];
};

/**
 * 响应式列
 */
const leftSpan = 1;
const { gridInstance, gridColumns } = useGridColumns(leftSpan);
const responsiveColumns = computeResponsiveColumns(300);
const rightSpan = computed(() => {
  const remainingColumns = gridColumns.value - leftSpan;
  return remainingColumns > 0 ? remainingColumns : leftSpan;
});

const { heightStyle } = useContentHeight();
</script>

<template>
  <div>
    <NGrid ref="gridInstance" x-gap="6" y-gap="6" :cols="responsiveColumns" responsive="self" item-responsive>
      <NGi :span="leftSpan">
        <NCard content-style="padding: 12px;" :style="heightStyle">
          <BasicTree
            :request="deptTreeSelect"
            list-field="data"
            @select="handleDepartmentSelect"
            @after-fetch="handleDepartmentAfterFetch"
          />
        </NCard>
      </NGi>
      <NGi :span="rightSpan">
        <BasicCrud
          :table-columns="columns"
          :form-schemas="formSchemas"
          :search-schemas="searchSchemas"
          :request="listUser"
          :request-params="requestParams"
          :create-request="addUser"
          :modify-request="updateUser"
          :delete-request="delUser"
          key-field="userId"
          :data-action-buttons="dataActionButtons"
        />
      </NGi>
    </NGrid>

    <BasicModal width="50vw" @register="register" @confirm="handleAssignRoles">
      <template #default>
        <BasicTable
          :request="listRole"
          :columns="roleColumns"
          :default-checked-row-keys="defaultSelectedRoles"
          value-field="roleId"
          pagination
          @check="handleSelectRoles"
        />
      </template>
    </BasicModal>
  </div>
</template>

<style lang="less" scoped></style>
